<template>
  <div class="notification-container">
    <!-- 通知权限请求 -->
    <div v-if="permissionStatus === 'default'" class="permission-request">
      <div class="permission-card">
        <div class="permission-icon">🔔</div>
        <h3>启用桌面通知</h3>
        <p>允许我们向您发送重要通知，让您及时了解工单状态和系统消息。</p>
        <div class="permission-actions">
          <button @click="requestPermission" class="btn-primary">
            启用通知
          </button>
          <button @click="dismissPermission" class="btn-secondary">
            稍后再说
          </button>
        </div>
      </div>
    </div>

    <!-- 通知设置 -->
    <div v-if="permissionStatus === 'granted'" class="notification-settings">
      <div class="settings-card">
        <h3>通知设置</h3>
        <div class="setting-item">
          <label>
            <input 
              type="checkbox" 
              v-model="settings.desktopNotifications"
              @change="updateSettings"
            >
            桌面通知
          </label>
        </div>
        <div class="setting-item">
          <label>
            <input 
              type="checkbox" 
              v-model="settings.soundNotifications"
              @change="updateSettings"
            >
            声音提示
          </label>
        </div>
        <div class="setting-item">
          <label>
            <input 
              type="checkbox" 
              v-model="settings.highPriorityOnly"
              @change="updateSettings"
            >
            仅高优先级通知
          </label>
        </div>
        <div class="setting-item">
          <label>
            <input 
              type="checkbox" 
              v-model="settings.ticketNotifications"
              @change="updateSettings"
            >
            工单通知
          </label>
        </div>
        <div class="setting-item">
          <label>
            <input 
              type="checkbox" 
              v-model="settings.systemNotifications"
              @change="updateSettings"
            >
            系统通知
          </label>
        </div>
      </div>
    </div>

    <!-- 通知历史 -->
    <div v-if="permissionStatus === 'granted'" class="notification-history">
      <div class="history-header">
        <h3>通知历史</h3>
        <div class="history-actions">
          <button @click="clearAllNotifications" class="btn-danger">
            清空所有
          </button>
          <button @click="markAllAsRead" class="btn-secondary">
            全部已读
          </button>
        </div>
      </div>
      
      <div class="notifications-list">
        <div 
          v-for="notification in recentNotifications" 
          :key="notification.id"
          :class="['notification-item', {
            'unread': !notification.isRead,
            'high-priority': notification.priority === 'high' || notification.priority === 'urgent'
          }]"
          @click="handleNotificationClick(notification)"
        >
          <div class="notification-icon">
            <span :class="getNotificationIcon(notification.type)">
              {{ getNotificationEmoji(notification.type) }}
            </span>
          </div>
          <div class="notification-content">
            <div class="notification-title">
              {{ notification.title }}
              <span v-if="!notification.isRead" class="unread-indicator">●</span>
            </div>
            <div class="notification-message">
              {{ notification.content }}
            </div>
            <div class="notification-meta">
              <span class="notification-time">
                {{ formatTime(notification.timestamp) }}
              </span>
              <span class="notification-category">
                {{ getCategoryName(notification.category) }}
              </span>
              <span v-if="notification.priority === 'high'" class="priority-badge">
                高优先级
              </span>
            </div>
          </div>
          <div class="notification-actions">
            <button 
              v-if="!notification.isRead"
              @click.stop="markAsRead(notification.id)"
              class="btn-mark-read"
              title="标记为已读"
            >
              ✓
            </button>
            <button 
              @click.stop="removeNotification(notification.id)"
              class="btn-remove"
              title="删除通知"
            >
              ×
            </button>
          </div>
        </div>
        
        <div v-if="recentNotifications.length === 0" class="empty-state">
          <div class="empty-icon">📭</div>
          <p>暂无通知</p>
        </div>
      </div>
    </div>

    <!-- 连接状态指示器 -->
    <div class="connection-status">
      <div :class="['status-indicator', {
        'connected': isConnected,
        'disconnected': !isConnected
      }]">
        <span class="status-dot"></span>
        <span class="status-text">
          {{ isConnected ? '实时连接' : '连接断开' }}
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useNotificationsStore } from '../store/notifications.js'
import messageHandler from '../services/notificationHandler.js'

export default {
  name: 'NotificationManager',
  setup() {
    const notificationsStore = useNotificationsStore()
    
    // 响应式数据
    const permissionStatus = ref('default')
    const settings = ref({
      desktopNotifications: true,
      soundNotifications: true,
      highPriorityOnly: false,
      ticketNotifications: true,
      systemNotifications: true
    })
    
    // 计算属性
    const recentNotifications = computed(() => notificationsStore.recentNotifications)
    const isConnected = computed(() => notificationsStore.isConnected)
    
    // 方法
    const checkPermission = () => {
      if ('Notification' in window) {
        permissionStatus.value = Notification.permission
      } else {
        permissionStatus.value = 'not-supported'
      }
    }
    
    const requestPermission = async () => {
      if ('Notification' in window) {
        try {
          const permission = await Notification.requestPermission()
          permissionStatus.value = permission
          
          if (permission === 'granted') {
            // 显示测试通知
            showTestNotification()
            loadSettings()
          }
        } catch (error) {
          console.error('❌ 请求通知权限失败:', error)
        }
      }
    }
    
    const dismissPermission = () => {
      permissionStatus.value = 'denied'
    }
    
    const showTestNotification = () => {
      if (Notification.permission === 'granted') {
        new Notification('通知已启用', {
          body: '您将收到重要的工单和系统通知',
          icon: '/favicon.ico'
        })
      }
    }
    
    const loadSettings = () => {
      const savedSettings = localStorage.getItem('notification-settings')
      if (savedSettings) {
        try {
          settings.value = { ...settings.value, ...JSON.parse(savedSettings) }
        } catch (error) {
          console.error('❌ 加载通知设置失败:', error)
        }
      }
    }
    
    const saveSettings = () => {
      try {
        localStorage.setItem('notification-settings', JSON.stringify(settings.value))
      } catch (error) {
        console.error('❌ 保存通知设置失败:', error)
      }
    }
    
    const updateSettings = () => {
      saveSettings()
    }
    
    const getNotificationIcon = (type) => {
      const iconMap = {
        'success': 'icon-success',
        'error': 'icon-error',
        'warning': 'icon-warning',
        'info': 'icon-info',
        'ticket': 'icon-ticket',
        'system': 'icon-system',
        'user': 'icon-user'
      }
      return iconMap[type] || 'icon-info'
    }
    
    const getNotificationEmoji = (type) => {
      const emojiMap = {
        'success': '✅',
        'error': '❌',
        'warning': '⚠️',
        'info': 'ℹ️',
        'ticket': '🎫',
        'system': '⚙️',
        'user': '👤'
      }
      return emojiMap[type] || '📢'
    }
    
    const getCategoryName = (category) => {
      const categoryMap = {
        'general': '一般',
        'ticket': '工单',
        'system': '系统',
        'user': '用户',
        'security': '安全'
      }
      return categoryMap[category] || category
    }
    
    const formatTime = (timestamp) => {
      const now = Date.now()
      const diff = now - timestamp
      
      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) { // 1天内
        return `${Math.floor(diff / 3600000)}小时前`
      } else {
        return new Date(timestamp).toLocaleDateString()
      }
    }
    
    const handleNotificationClick = (notification) => {
      // 标记为已读
      if (!notification.isRead) {
        markAsRead(notification.id)
      }
      
      // 根据通知类型进行不同的处理
      const { category, data } = notification
      
      switch (category) {
        case 'ticket':
          if (data.ticketId) {
            window.location.href = `/ticket/${data.ticketId}`
          }
          break
        case 'user':
          window.location.href = '/users'
          break
        case 'system':
          window.location.href = '/settings'
          break
        default:
          window.location.href = '/notifications'
      }
    }
    
    const markAsRead = (notificationId) => {
      notificationsStore.markAsRead(notificationId)
      messageHandler.markAsRead(notificationId)
    }
    
    const markAllAsRead = () => {
      notificationsStore.markAllAsRead()
    }
    
    const removeNotification = (notificationId) => {
      notificationsStore.removeNotification(notificationId)
    }
    
    const clearAllNotifications = () => {
      if (confirm('确定要清空所有通知吗？')) {
        notificationsStore.clearAllNotifications()
      }
    }
    
    // 监听WebSocket连接状态
    const updateConnectionState = (connected) => {
      notificationsStore.setConnectionState(connected)
    }
    
    // 生命周期
    onMounted(() => {
      checkPermission()
      loadSettings()
      notificationsStore.initialize()
      
      // 启动消息处理器
      messageHandler.start()
      
      // 监听连接状态变化
      messageHandler.on('connected', () => updateConnectionState(true))
      messageHandler.on('disconnected', () => updateConnectionState(false))
    })
    
    onUnmounted(() => {
      // 停止消息处理器
      messageHandler.stop()
    })
    
    return {
      permissionStatus,
      settings,
      recentNotifications,
      isConnected,
      requestPermission,
      dismissPermission,
      updateSettings,
      getNotificationIcon,
      getNotificationEmoji,
      getCategoryName,
      formatTime,
      handleNotificationClick,
      markAsRead,
      markAllAsRead,
      removeNotification,
      clearAllNotifications
    }
  }
}
</script>

<style scoped>
.notification-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.permission-request {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.permission-card {
  background: white;
  border-radius: 12px;
  padding: 40px;
  text-align: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  max-width: 400px;
}

.permission-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.permission-card h3 {
  margin: 0 0 16px 0;
  color: #333;
}

.permission-card p {
  color: #666;
  margin-bottom: 24px;
  line-height: 1.5;
}

.permission-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.btn-primary, .btn-secondary, .btn-danger {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover {
  background: #0056b3;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #545b62;
}

.btn-danger {
  background: #dc3545;
  color: white;
}

.btn-danger:hover {
  background: #c82333;
}

.notification-settings {
  margin-bottom: 30px;
}

.settings-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.settings-card h3 {
  margin: 0 0 20px 0;
  color: #333;
}

.setting-item {
  margin-bottom: 16px;
}

.setting-item label {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
}

.setting-item input[type="checkbox"] {
  margin-right: 8px;
}

.notification-history {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.history-header h3 {
  margin: 0;
  color: #333;
}

.history-actions {
  display: flex;
  gap: 8px;
}

.notifications-list {
  max-height: 400px;
  overflow-y: auto;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  padding: 16px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.2s;
}

.notification-item:hover {
  background-color: #f8f9fa;
}

.notification-item.unread {
  background-color: #f0f8ff;
  border-left: 4px solid #007bff;
}

.notification-item.high-priority {
  border-left: 4px solid #dc3545;
}

.notification-icon {
  margin-right: 12px;
  font-size: 20px;
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-title {
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.unread-indicator {
  color: #007bff;
  font-size: 12px;
}

.notification-message {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
  line-height: 1.4;
}

.notification-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #999;
}

.priority-badge {
  background: #dc3545;
  color: white;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 10px;
}

.notification-actions {
  display: flex;
  gap: 4px;
  margin-left: 12px;
}

.btn-mark-read, .btn-remove {
  width: 24px;
  height: 24px;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.btn-mark-read {
  background: #28a745;
  color: white;
}

.btn-mark-read:hover {
  background: #218838;
}

.btn-remove {
  background: #dc3545;
  color: white;
}

.btn-remove:hover {
  background: #c82333;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #666;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.connection-status {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 1000;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.status-indicator.connected {
  background: #d4edda;
  color: #155724;
}

.status-indicator.disconnected {
  background: #f8d7da;
  color: #721c24;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: currentColor;
}

.status-indicator.connected .status-dot {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}
</style>
